/*
 * This class is tree node structure.  It is used in the first level of Range Tree.
 * It is a subclass of Node.  The main difference is that an associated tree is also attached to this node.
 */

package MyTree;

import java.awt.Point;
import java.util.ArrayList;

import MyAssoTree.MyAssoNode;
import MyAssoTree.MyAssoTree;
import Red_Black_Tree.Node;

public class MyNode extends Node{

	private Point key;
	private MyAssoTree asso;
	
	public MyNode(int x, int y) {
		super();
		key = new Point(x, y);
	}
	// constructor for leaf node
	public MyNode(){
		super();
	}
	
//	public Point getKey(){
//		return key;
//	}
	
	public int getX(){
		return key.x;
	}
	public int getY(){
		return key.y;
	}

	@Override
	/*
	 * Basic method for comparing two nodes according to their keys.
	 * DEFINE: If current key is larger than n's key, return 1;
	 *         If current key is equal to n's key, return 0;
	 *         If current key is less than n's key, return -1.
	 * This version compares two points according to their x coordinate.
	 * For points with same x coordinate, the one with bigger y coordinate is of priority.
	 */ 
	public int compareTo(Node n) {
		MyNode n2 = (MyNode) n;
		if (this.key.x > n2.getX())
			return 1;
		else if (this.key.x < n2.getX())
			return -1;
		else if (this.key.x == n2.getX() && this.key.y > n2.getY())
			return 1;
		else if (this.key.x == n2.getX() && this.key.y < n2.getY())
			return -1;
		else 
			return 0;
	}	
	// this version compares current node to another key word, using same scheme as above
	public int compareTo (Point k2) {
		if (key.x > k2.x)
			return 1;
		else if (key.x < k2.x)
			return -1;
		else if (key.x == k2.x && key.y > k2.y)
			return 1;
		else if (key.x == k2.x && key.y < k2.y)
			return -1;
		else 
			return 0;
	}

	/*
	 * Build associate tree for this node.
	 * Input: the subtree associated with this node
	 * Output: a BST of these nodes, built according to their y-coordinage
	 */
	public void buildAssoTree(){
		ArrayList<Node> subtree = new ArrayList<Node>();
		traverseSubtree(this, subtree);
		
		asso = new MyAssoTree();
		if(!subtree.isEmpty())
			for(Node n : subtree){
				MyNode n2 = (MyNode) n;
				asso.insert(new MyAssoNode(n2.getX(), n2.getY()));
			}
		else
			System.out.println("Error at buildAssoTree");
	}
	
	/*
	 * Traverse the subtree associated with current node,
	 * add them into the array.
	 */
	private void traverseSubtree(Node n, ArrayList<Node> array){
		if(!n.isLeaf()){
			array.add(n);
			traverseSubtree(n.getLChild(), array);
			traverseSubtree(n.getRChild(), array);
		}
	}
	
	public void query(int ymin, int ymax, ArrayList<Point> report){
		asso.query(ymin, ymax, report);		
	}
}



















